import {
    Image,
    StyleSheet,
    View,
    Text,
    TouchableOpacity,
    Button,
    TextInput,
    Platform,
    TouchableWithoutFeedback,
    Keyboard,
    KeyboardAvoidingView,
    ScrollView
} from 'react-native';
import { useSelector, useDispatch } from 'react-redux';
import { RootState, AppDispatch } from '@/store';
import {router, Stack, useRouter} from 'expo-router';
import {useEffect, useState, useRef} from "react";
import Checkbox from 'expo-checkbox';
import { showToast } from "@/utils/rootToast";
import { validationPhoneSchema } from "@/utils/validatationSchema"
import { postLogin } from '@/services/login'
import DeviceInfo from 'react-native-device-info';

import { addPhone, setLoginInfo } from "@/store/slices/loginSlice"

// import CheckBox from '@react-native-community/checkbox';

import AntDesign from '@expo/vector-icons/AntDesign';
import EvilIcons from '@expo/vector-icons/EvilIcons';
import headerBg from "@/assets/images/login/header_bg.png"
import {scaleSize} from "@/utils/screenSize";

export default function LoginScreen() {
    const [phone, setPhone] = useState("");
    const [selectAgree, setSelectAgree] = useState(false);
    const login = useSelector((state: RootState) => state.login);
    const dispatch = useDispatch<AppDispatch>();
    const refInput = useRef(null);

    useEffect(() => {
        // router.push("/verifyCode")
    }, [])

    const goCode = async function () {
        // router.push("/verifyCode")
        if (phone.length < 11) return;
        try {
            // 执行验证
            await validationPhoneSchema.validate({ phone }, { abortEarly: false });
            dispatch(addPhone({ phone }))
            if (selectAgree) {
                router.push("/verifyCode")
                // const uniqueId = DeviceInfo.getUniqueId();
                // const model = DeviceInfo.getModel();

                const uniqueId = await DeviceInfo.getUniqueId();
                const model = DeviceInfo.getModel();

                console.log('uniqueId', uniqueId);

                const data = {
                    "mobile":phone,
                    "deviceType": Platform?.OS == 'ios' ? 1 : 2,
                    "deviceId": uniqueId || "",
                    "deviceModel": model,
                    "osVersion": Platform?.Version,
                    "appVersion": "1.0.0"
                };
                dispatch(setLoginInfo({ loginInfo: data }))

                //
                // postLogin(data)
                //     .then(res => {
                //         console.log('res', res);
                //
                //     })
                //     .catch(err => {
                //         console.log('err', err);
                //     })
            } else {
                showToast("请阅读《用户协议》和 《隐私政策》")
                refInput?.current?.blur();

            };

        } catch (err) {
            if (err.inner) {
                // 将错误信息映射到状态
                const newErrors = err.inner.reduce((acc, curr) => {
                    acc[curr.path] = curr.message;
                    return acc;
                }, {});
                showToast(newErrors.phone);
            }
        }
    };

    const goUserAgreement = function () {
        router.push("/setting/userAgreement");
    };

    // 过渡动画配置
    const forSlideFromBottom = ({ current, next, layouts }) => {
        const translateY = current.progress.interpolate({
            inputRange: [0, 1],
            outputRange: [layouts.screen.height, 0],
        });

        return {
            cardStyle: {
                transform: [{ translateY }],
            },
        };
    };

    const transitionSpec = {
        open: { animation: 'spring', config: { duration: 300 } },
        close: { animation: 'spring', config: { duration: 300 } },
    };

    const goMeetQuestion = function () {
        router.push("/meetQuestion")
    };

    const privacyAgreement = function () {
        router.push("/setting/privacyAgreement");
    };

    const focusInputFuc = function () {

        console.log(refInput.current)
    };


    return (
        <ScrollView  style={{ backgroundColor: "#fff", height: "100%", flex: 1 }}>
            <Stack.Screen
                options={{ headerShown: false}}
            />
            <TouchableOpacity onPress={Keyboard.dismiss} activeOpacity={1}>
                <View style={styles.headerTitle}>
                    <Text style={styles.headerText}>欢迎登录超维娱网</Text>
                </View>
                <View style={styles.headerBg}>
                    <Image source={headerBg} style={styles.img} />
                </View>
                <View style={styles.phoneContainer}>
                    <View style={styles.phoneInput}>
                        <View style={{ flexDirection: 'row', alignItems: 'center' }}>
                            <Text style={{ fontSize: 14 }}>+86</Text>
                            {/*<View style={{ marginLeft: 4 }}>*/}
                            {/*    <AntDesign name="down" size={14} color="black" />*/}
                            {/*</View>*/}
                        </View>
                        <TextInput
                            style={{ letterSpacing: 1.5,marginLeft: 10 ,height: 40, borderColor: 'transparent', borderWidth: 1, width: 200, fontSize: 16, color: "#2A2B30" }}
                            placeholder="请输入手机号码"
                            clearButtonMode={"while-editing"}
                            value={phone}
                            onChangeText={(v: any) =>  {
                                setPhone(v);
                            }}
                            ref={refInput}
                        />

                    </View>
                    <View style={{ marginLeft: 29, marginTop: 10 }}>
                        <Text style={styles.phoneTip}>未注册的手机号验证后自动创建账号</Text>
                    </View>
                    <View style={phone.length >= 11 ? styles.getCode_active : styles.getCode } >
                        <TouchableOpacity activeOpacity={1} onPress={goCode}>
                            <Text style={phone.length >= 11 ? styles.getCodeText_ative : styles.getCodeText }>获取短信验证码</Text>
                        </TouchableOpacity>
                    </View>
                    <TouchableOpacity onPress={goMeetQuestion}>
                        <View style={styles.question}>
                            <Text style={styles.questionText}>遇到问题</Text>
                            <EvilIcons name="question" size={18} color="#9C9EAC" />
                        </View>
                    </TouchableOpacity>


                </View>
            </TouchableOpacity>

            <TouchableOpacity style={styles.agreeWrap} onPress={Keyboard.dismiss} activeOpacity={1}>
                <Checkbox
                    style={styles.agreeCircle}
                    value={selectAgree} onValueChange={(V: any) => (setSelectAgree(V))}
                    color={selectAgree ? '#EC6138' : "#333"}
                />
                <View style={styles.agreeText}>
                    <Text style={{ fontSize: 14, }}>我已阅读并同意</Text>
                    <TouchableOpacity onPress={goUserAgreement} style={styles.ThemeColor}>
                        <Text style={styles.ThemeColor}>《用户协议》</Text>
                    </TouchableOpacity><Text style={{ fontSize: 14, }}>和</Text><TouchableOpacity onPress={privacyAgreement}><Text style={styles.ThemeColor}>《隐私政策》</Text></TouchableOpacity>
                </View>
            </TouchableOpacity>
        </ScrollView>

    );
}

const styles = StyleSheet.create({
    headerBg: {
        width: "100%",
        height: 400,
    },
    img: {
        width: '100%',
        height: '100%'

    },
    headerTitle: {
        position: "absolute",
        left: 29,
        top: 171,
    },
    headerText: {
        fontSize: 24,
        color: "#2A2B30",
        fontWeight: "bold",
        fontFamily: "PingFang SC, PingFang SC",
    },
    phoneContainer: {
        position: "absolute",
        top: 257,
        width: "100%"
    },
    phoneInput: {
        flexDirection: "row",
        alignItems: "center",
        width: 340,
        paddingBottom: 9,
        borderBottomWidth: 1,
        borderBottomColor: "#EEE",
        marginLeft: 30,
    },
    phoneTip: {
        fontSize: 12,
        color: "#9C9EAC",
    },
    getCode_active: {
        margin: "auto",
        // flexDirection: 'row',
        // alignItems: "center",
        // justifyContent: "center",
        width: scaleSize(317),
        height: 50,
        backgroundColor: "#EC6138",
        borderRadius: 46,
        marginTop: 70
    },
    getCode: {
        margin: "auto",
        // flexDirection: 'row',
        // alignItems: "center",
        // justifyContent: "center",
        width: scaleSize(317),
        height: 50,
        backgroundColor: "#f5f5f5",
        borderRadius: 46,
        marginTop: 70
    },
    getCodeText_ative: {
        color: "#FFF",
        fontSize: 14,
        display: "flex",
        width: "100%",
        height: "100%",
        textAlign: "center",
        lineHeight: 50,
    },
    getCodeText: {
        color: "rgba(0, 0, 0, 0.25)",
        fontSize: 14,
        display: "flex",
        width: "100%",
        height: "100%",
        textAlign: "center",
        lineHeight: 50,
    },
    question: {
        flexDirection: "row",
        marginLeft: 280,
        marginTop: 10,
    },
    questionText: {
        fontSize: 12,
        color: "#9C9EAC",

    },
    agreeWrap: {
        flexDirection: "row",
        alignItems: "center",
        marginTop: 350,
        marginLeft: 58,
        // position: "absolute",
        // bottom: 91,
        // marginTop: 258,
    },
    agreeCircle: {
        color: "#333",
        borderRadius: 50,
        borderWidth: 1,
        width: 13,
        height: 13,
        marginRight: 2,
        borderColor: "#333333"
    },
    agreeText: {
        color: "#333",
        fontSize: 14,
        marginLeft: 5,
        flexDirection: "row",
        alignItems: "center",
    },
    ThemeColor: {
        color: "#EC6138",
        fontSize: 14,
    },
});
